package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.enums.StatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-09-30
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {

        //取出手机号 验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //判断手机号,验证码是否为空
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new YyghException(20001,"手机号或验证码不能为空!");
        }

        //校验验证码
        String realCode = redisTemplate.opsForValue().get(phone);
        if(StringUtils.isEmpty(realCode) || !realCode.equals(code)){
            throw new YyghException(200001,"验证码不正确!");
        }
        //判断账户是否存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        //手机号登录
        if(StringUtils.isEmpty(loginVo.getOpenid())){
            if(userInfo == null){
                //账户不存在,新建账户
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }else {
            //微信登录
            QueryWrapper<UserInfo> query = new QueryWrapper<>();
            query.eq("openid",loginVo.getOpenid());
            //微信登录 ,绑定手机号
            if(userInfo == null){
                userInfo = baseMapper.selectOne(query);
                userInfo.setPhone(phone);
                baseMapper.updateById(userInfo);
            }else {
                UserInfo info = baseMapper.selectOne(query);
                userInfo.setNickName(info.getNickName());
                userInfo.setOpenid(info.getOpenid());
                //修改手机号账户,把微信昵称等信息复制进去
                baseMapper.updateById(userInfo);
                //删除创建的微信账户
                baseMapper.deleteById(info.getId());
            }
        }
        
        //校验账户状态
        if(userInfo.getStatus() == 0){
            throw new YyghException(20001,"你的账号已锁定!请联系管理员!");
        }
        //返回登录信息
        HashMap<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        //获取登录凭证
        String token = JwtHelper.createToken(userInfo.getId(),name);
        map.put("name",name);
        map.put("token",token);
        return map;
    }

    @Override
    public Map<String, String> WXlogin(String openid, String nickname) {
        //判断是否是第一次微信登录
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setOpenid(openid);
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        //校验账户状态
        if(userInfo.getStatus() == 0){
            throw new YyghException(20001,"你的账号已锁定!请联系管理员!");
        }
        //返回登录信息
        HashMap<String, String> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }
        if (!StringUtils.isEmpty(userInfo.getPhone())){
            //不需要绑定手机号
            openid = "";
        }
        //获取登录凭证
        String token = JwtHelper.createToken(userInfo.getId(),name);
        map.put("name",name);
        map.put("openid",openid);
        map.put("token",token);
        return map;
    }

    @Override
    public Page<UserInfo> findPageList(Integer pageNum, Integer pageSize, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> page = new Page<>(pageNum, pageSize);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        String keyword = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        if(!StringUtils.isEmpty(keyword)){
            queryWrapper.and(que -> que.like("name",keyword).or().eq("phone",keyword));
        }
        //queryWrapper.like(!StringUtils.isEmpty(keyword),"name",keyword).or().eq(!StringUtils.isEmpty(keyword),"phone",keyword);
        queryWrapper.eq(!StringUtils.isEmpty(status),"status",status);
        queryWrapper.eq(!StringUtils.isEmpty(authStatus),"auth_status",authStatus);
        queryWrapper.ge(!StringUtils.isEmpty(createTimeBegin),"create_time",createTimeBegin);
        queryWrapper.le(!StringUtils.isEmpty(createTimeEnd),"create_time",createTimeEnd);
        page = baseMapper.selectPage(page,queryWrapper);
        page.getRecords().forEach(item ->{
            item.getParam().put("statusString", StatusEnum.getNameByStatus(item.getStatus()));
            item.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(item.getAuthStatus()));
        });
        return page;
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if(status == 0 || status == 1){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public void updateAuthStatus(Long id, Integer authStatus) {
        if(authStatus == 2 || authStatus == -1){
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> detail(Long userId) {
        Map<String, Object> map = new HashMap<>();
        //查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        map.put("userInfo",userInfo);

        //查询就诊人信息
        List<Patient> patientList = patientService.selectListByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }
}
